package co.edu.eam.iso.view;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import co.edu.eam.iso.dao.MetricDAO;
import co.edu.eam.iso.enums.ActionEnum;
import co.edu.eam.iso.enums.CharacteristicEnum;
import co.edu.eam.iso.enums.SubCharacteristicEnum;
import co.edu.eam.iso.evaluator.Metric;

public class ModalMetric extends JDialog {

	private static final long serialVersionUID = 1L;
	
	private static final int METRIC_MAX_LENGTH = 200;
	
	private final JPanel contentPanel = new JPanel();
	
	private JTextArea txtDescription;
	
	private MetricDAO metricDAO;
	private JComboBox cbCharacteristics;
	private JComboBox cbSubcharacteristics;
	
	private String titleModal;	
	private String titleButton;	
	private String titlePanel;
	
	private Metric metric;
	
	private ActionEnum actionParent;
	
	private CharacteristicEnum characteristicSelected;

	/**
	 * Create the dialog.
	 * @param characteristicSelected 
	 */
	public ModalMetric(ManageMetrics parent, Metric metric,
			ActionEnum actionParent, CharacteristicEnum characteristicSelected) {
		this.metric = metric;
		this.actionParent = actionParent;
		this.characteristicSelected = characteristicSelected;
		metricDAO = new MetricDAO();

		determinateTitles();
		initialize(parent);
	}
	
	private void initialize(ManageMetrics parent) {
		setTitle(titleModal);
		setResizable(false);
		setModal(true);
		setBounds(100, 100, 380, 334);
		setLocationRelativeTo(parent);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		contentPanel.add(createPanelAction());
		
		JButton btnAction = new JButton(titleButton);
		btnAction.setBounds(277, 271, 90, 25);
		contentPanel.add(btnAction);
		btnAction.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (metric != null) {
					editMetric();
				} else {
					createMetric();
				}
			}
		});

		JButton btnCancel = new JButton("Cancelar");
		btnCancel.setBounds(180, 271, 90, 25);
		contentPanel.add(btnCancel);
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
	}
	
	private JPanel createPanelAction() {
		JPanel panelAction = new JPanel();
		panelAction.setBorder(new TitledBorder(null, titlePanel,
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelAction.setBounds(5, 5, 362, 255);
		panelAction.setLayout(null);
		
		txtDescription = new JTextArea();
		txtDescription.setBounds(20, 125, 324, 115);
		txtDescription.setRows(2);
		txtDescription.setLineWrap(true);
		txtDescription.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent e) {
				if (txtDescription.getText().length() == METRIC_MAX_LENGTH) {
					e.consume();
				}
			}

			public void keyReleased(KeyEvent e) {
				if (e.getKeyChar() == KeyEvent.VK_ENTER
						|| e.getKeyChar() == KeyEvent.VK_TAB) {
					String str = txtDescription.getText()
							.replaceAll("\n", "").replaceAll("\t", "");
					txtDescription.setText(str);
				}
			}
		});
		panelAction.add(txtDescription);
		
		cbSubcharacteristics = new JComboBox();
		cbSubcharacteristics.addItem("Seleccione");
		cbSubcharacteristics.setBounds(190, 50, 154, 25);
		panelAction.add(cbSubcharacteristics);

		if (ActionEnum.MANAGE == actionParent) {
			cbCharacteristics = new JComboBox();
			cbCharacteristics.setBounds(20, 50, 154, 25);
			cbCharacteristics.addItem("Seleccione");
			loadCharacteristics();
			cbCharacteristics.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					cbSubcharacteristics.removeAllItems();
					cbSubcharacteristics.addItem("Seleccione");		

					loadSubCharacteristics(cbCharacteristics.getSelectedIndex());
				}
			});
			panelAction.add(cbCharacteristics);
			
			if (metric != null) {
				cbCharacteristics.setSelectedIndex(metric
						.getSubCharacteristicEnum().getCharacteristicEnum().getId());
			}						
		} else if (ActionEnum.SELECT == actionParent) {
			JTextField txtCharacteristic = new JTextField();
			txtCharacteristic.setText(characteristicSelected.toString());
			txtCharacteristic.setEditable(false);
			txtCharacteristic.setBounds(20, 50, 160, 25);
			panelAction.add(txtCharacteristic);		
			
			loadSubCharacteristics(characteristicSelected.getId());
		}
		
		if (metric != null) {			
			cbSubcharacteristics.setSelectedIndex(metric
					.getSubCharacteristicEnum().getOrder());
			txtDescription.setText(metric.getDescription());
		}

		JLabel lblSubcharacteristic = new JLabel("Sub-característica");
		lblSubcharacteristic.setBounds(190, 25, 116, 14);
		lblSubcharacteristic.setFont(new Font("Tahoma", Font.BOLD, 11));
		panelAction.add(lblSubcharacteristic);

		JLabel lblCharacteristic = new JLabel("Característica");
		lblCharacteristic.setBounds(20, 25, 91, 14);
		lblCharacteristic.setFont(new Font("Tahoma", Font.BOLD, 11));
		panelAction.add(lblCharacteristic);

		JLabel lblDescription = new JLabel("Descripción:");
		lblDescription.setBounds(20, 100, 80, 14);
		lblDescription.setFont(new Font("Tahoma", Font.BOLD, 11));
		panelAction.add(lblDescription);
		
		return panelAction;
	}
	
	private void createMetric() {
		if (validateFields()) {
			SubCharacteristicEnum subCharacteristic = (SubCharacteristicEnum) cbSubcharacteristics
					.getSelectedItem();

			metricDAO.createMetric(txtDescription.getText(),
					subCharacteristic.getId());

			JOptionPane.showMessageDialog(this, "Se creó la métrica exitosamente",
					"Mensaje de información", JOptionPane.INFORMATION_MESSAGE);
			dispose();
		} else {
			JOptionPane.showMessageDialog(this,
					"Todos los campos son requeridos", "Mensaje de error",
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void editMetric() {
		if (validateFields()) {
			String description = txtDescription.getText();
			SubCharacteristicEnum subCharacteristic = (SubCharacteristicEnum) cbSubcharacteristics
					.getSelectedItem();

			metricDAO.updateMetric(metric.getId(), description,
					subCharacteristic.getId());
			
			JOptionPane.showMessageDialog(this, "Se ha modificado la métrica",
					"Mensaje de información", JOptionPane.INFORMATION_MESSAGE);
			dispose();
		} else {
			JOptionPane.showMessageDialog(this,
					"Todos los campos son requeridos", "Mensaje de error",
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void determinateTitles() {
		if (metric != null) {
			titleButton = "Editar";
			titleModal = "ISO 9126-1 - Editar métrica";
			titlePanel = "Editar métrica";			
		} else {
			titleButton = "Crear";
			titleModal = "ISO 9126-1 - Crear métrica";
			titlePanel = "Crear métrica";			
		}
	}
	
	private boolean validateFields() {
		boolean characteristicSelected = true;
		if (ActionEnum.MANAGE == actionParent) {
			characteristicSelected = cbCharacteristics.getSelectedIndex() != 0;
		}

		return characteristicSelected
				&& cbSubcharacteristics.getSelectedIndex() != 0
				&& txtDescription.getText().length() != 0;
	}
	
	private void loadCharacteristics() {
		for (CharacteristicEnum characteristic : CharacteristicEnum.values()) {
			cbCharacteristics.addItem(characteristic);
		}
	}
	
	private void loadSubCharacteristics(int idCharacteristic) {
		for (SubCharacteristicEnum subCharacteristic : SubCharacteristicEnum
				.getByIdCharacteristic(idCharacteristic)) {
			cbSubcharacteristics.addItem(subCharacteristic);
		}
	}
}
